package com.qidian.by.goods.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.qidian.by.goods.dto.SpeInfo;
import com.qidian.by.goods.mapper.ItemSpecificationMapper;
import com.qidian.by.goods.service.IItemSpecificationService;
import com.qidian.by.goods.vo.ItemAndSpeRelationVO;
import com.qidian.by.pojo.goods.entity.ItemSpecification;
import com.qidian.by.util.exceptions.ServiceExceptionEnum;
import com.qidian.by.util.pojo.EsResult;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 小可怎么都睡不够
 * @since 2024-05-08
 */
@Service
public class ItemSpecificationServiceImpl extends BaseServiceImpl<ItemSpecification>  implements IItemSpecificationService {
    @Autowired
    private ItemSpecificationMapper speMapper;
    @Override
    public EsResult save(ItemSpecification spe) {
        QueryWrapper<ItemSpecification> wrapper = new QueryWrapper<>();
        wrapper.eq("spe_name",spe.getSpeName());
        ItemSpecification itemSpecification = speMapper.selectOne(wrapper);
        if (itemSpecification != null){
            return EsResult.error(ServiceExceptionEnum.DEFAULT_FAIL);
        }else{
            return EsResult.isSuccess(speMapper.insert(spe));
        }
    }

    @Override
    public EsResult<IPage<ItemSpecification>> list(ItemSpecification spe, int page, int limit) {
        IPage<ItemSpecification> iPage = getPage(page,limit);
        QueryWrapper<ItemSpecification> wrapper = new QueryWrapper<>();
        wrapper.like(spe != null && !StringUtils.isBlank(spe.getSpeName()),"spe_name",spe.getSpeName());
        return EsResult.ok("查询成功",speMapper.selectPage(iPage,wrapper));
    }

    @Override
    @Transactional
    public EsResult replace(ItemAndSpeRelationVO vo) {
        speMapper.deleteAllByItemId(Long.valueOf(vo.getItemId()));
        List<SpeInfo> res = new ArrayList<>();
        vo.getSpeId().forEach(speId -> {
            res.add(new SpeInfo(Long.valueOf(speId), Long.valueOf(vo.getItemId())));
        });
        speMapper.addSpes(res);
        return EsResult.ok();
    }

}
